import { Component, ElementRef, ViewChild } from '@angular/core';
import { CheeseToolService } from '../../projects/cheese-tool/src/lib/service/cheese-tool.service';
import { CheeseToastService } from 'projects/cheese-tool/src/public-api';
import { CheesePopupTipService } from 'projects/cheese-tool/src/lib/popup-tip/public-api';

interface DataItem {
  title: string;
  value: string;
}

interface CategoryItem {
  name: string;
  color: string;
  active: boolean;
}

interface Category {
  name: string;
  items: CategoryItem[];
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent {
  @ViewChild('submitBtn', { static: false }) submitBtn!: ElementRef;
  
  apiResponse: 'success' | 'error' = 'success';
  showit = false;

  title = 'cheese-tools';
  isLoading = true;
  searchText = '我是文字'

  progressValue: number = 0;
  progressTotal: number = 100;
  precision: number = 2;
  useCustomColor: boolean = false;


  position: 'top-center' | 'top-right' | 'bottom-center' | 'bottom-right' = 'top-center';
  duration = 3000;
  closable = false;

  // 用于直接输入百分比的测试
  percentageValue: string = "0";

  // 用于动态内容变化测试
  currentTime: string = new Date().toLocaleTimeString();
  showSpecialMessage: boolean = false;

  // 用于ngFor测试
  dataItems: DataItem[] = [
    { title: '温度', value: '26°C' },
    { title: '湿度', value: '45%' },
    { title: '风速', value: '3m/s' }
  ];

  // 用于ngIf测试
  systemStatus: 'online' | 'offline' = 'online';
  responseTime: number = 120;
  recoveryTime: string = '17:30:00';
  userCount: number = 45;

  // 用于复杂嵌套ngIf和ngFor测试
  categories: Category[] = [
    {
      name: '水果',
      items: [
        { name: '苹果', color: 'red', active: true },
        { name: '香蕉', color: 'yellow', active: true },
        { name: '橙子', color: 'orange', active: false }
      ]
    },
    {
      name: '蔬菜',
      items: [
        { name: '胡萝卜', color: 'orange', active: true },
        { name: '西兰花', color: 'green', active: false },
        { name: '茄子', color: 'purple', active: true }
      ]
    }
  ];

  constructor(public cs: CheeseToolService, public toastService: CheeseToastService,private popupTipService: CheesePopupTipService) {
    // 每秒自动更新一次时间，模拟实时数据
    setInterval(() => {
      this.updateCurrentTime();
    }, 5000);
  }

  toggleLoading() {
    this.isLoading = !this.isLoading;
  }

  i: number = 0
  change() {
    this.i++
  }

  
  showSuccessToast() {
    this.toastService.success('操作成功！', this.getConfig());
  }
  
  showErrorToast() {
    this.toastService.error('操作失败！', this.getConfig());
  }
  
  showInfoToast() {
    this.toastService.info('这是一条信息提示', this.getConfig());
  }
  
  showWarningToast() {
    this.toastService.warning('这是一条警告提示', this.getConfig());
  }
  
  private getConfig() {
    return {
      position: this.position,
      duration: this.duration,
      closable: this.closable
    };
  }

  submitForm() {
    // 模拟API调用
    setTimeout(() => {
      if (this.apiResponse === 'success') {
        this.popupTipService.success(this.submitBtn, '提交成功！', {
          duration: 3000,
          position: 'top'
        });
      } else {
        this.popupTipService.error(this.submitBtn, '提交失败！', {
          duration: 3000,
          position: 'top'
        });
      }
    }, 1000); // 模拟网络延迟
  }

  show() {
    this.showit = !this.showit;
  }

  // 切换特殊消息的显示状态
  toggleSpecialMessage() {
    this.showSpecialMessage = !this.showSpecialMessage;
  }

  // 更新当前时间
  updateCurrentTime() {
    this.currentTime = new Date().toLocaleTimeString();
  }

  // ngFor测试的方法
  addDataItem() {
    const newItems = ['压力', '光照', '噪音', 'PM2.5', '二氧化碳'];
    const randomValues = ['12.5kPa', '850lux', '62dB', '35μg/m³', '420ppm'];
    
    if (this.dataItems.length < 7) {
      const randomIndex = Math.floor(Math.random() * newItems.length);
      this.dataItems.push({
        title: newItems[randomIndex],
        value: randomValues[randomIndex]
      });
    }
  }

  removeDataItem() {
    if (this.dataItems.length > 1) {
      this.dataItems.pop();
    }
  }

  updateDataItems() {
    // 更新所有数据项的值
    this.dataItems = this.dataItems.map(item => {
      let newValue: string;
      
      switch (item.title) {
        case '温度':
          newValue = `${Math.floor(20 + Math.random() * 15)}°C`;
          break;
        case '湿度':
          newValue = `${Math.floor(30 + Math.random() * 60)}%`;
          break;
        case '风速':
          newValue = `${(1 + Math.random() * 8).toFixed(1)}m/s`;
          break;
        case '压力':
          newValue = `${(10 + Math.random() * 5).toFixed(1)}kPa`;
          break;
        case '光照':
          newValue = `${Math.floor(500 + Math.random() * 1000)}lux`;
          break;
        case '噪音':
          newValue = `${Math.floor(40 + Math.random() * 50)}dB`;
          break;
        case 'PM2.5':
          newValue = `${Math.floor(10 + Math.random() * 90)}μg/m³`;
          break;
        case '二氧化碳':
          newValue = `${Math.floor(350 + Math.random() * 300)}ppm`;
          break;
        default:
          newValue = item.value;
      }
      
      return { ...item, value: newValue };
    });
  }

  // ngIf测试的方法
  toggleSystemStatus() {
    this.systemStatus = this.systemStatus === 'online' ? 'offline' : 'online';
    console.log('系统状态切换为:', this.systemStatus);
  }

  updateSystemMetrics() {
    if (this.systemStatus === 'online') {
      this.responseTime = Math.floor(50 + Math.random() * 200);
      this.userCount = this.userCount > 0 ? Math.floor(10 + Math.random() * 100) : 0;
    } else {
      const now = new Date();
      now.setMinutes(now.getMinutes() + Math.floor(Math.random() * 60));
      this.recoveryTime = now.toLocaleTimeString();
    }
    console.log('系统指标已更新');
  }

  toggleUserCount() {
    this.userCount = this.userCount > 0 ? 0 : Math.floor(10 + Math.random() * 100);
    console.log('用户显示已切换，当前值:', this.userCount);
  }

  // 复杂嵌套ngIf和ngFor测试的方法
  toggleCategoryItems() {
    // 切换所有项目的活跃状态
    this.categories.forEach(category => {
      category.items.forEach(item => {
        item.active = !item.active;
      });
    });
  }

  addNewCategory() {
    const newCategoryNames = ['饮料', '零食', '日用品', '电子产品', '文具'];
    const existingNames = this.categories.map(c => c.name);
    
    // 找到一个不存在的分类名
    const availableNames = newCategoryNames.filter(name => !existingNames.includes(name));
    
    if (availableNames.length > 0) {
      const randomName = availableNames[Math.floor(Math.random() * availableNames.length)];
      let newItems: CategoryItem[] = [];
      
      // 根据分类名创建不同的项目
      switch (randomName) {
        case '饮料':
          newItems = [
            { name: '咖啡', color: 'brown', active: true },
            { name: '茶', color: 'green', active: false },
            { name: '可乐', color: 'black', active: true }
          ];
          break;
        case '零食':
          newItems = [
            { name: '薯片', color: 'gold', active: true },
            { name: '巧克力', color: 'brown', active: true },
            { name: '饼干', color: 'tan', active: false }
          ];
          break;
        case '日用品':
          newItems = [
            { name: '牙刷', color: 'blue', active: true },
            { name: '肥皂', color: 'white', active: false }
          ];
          break;
        case '电子产品':
          newItems = [
            { name: '手机', color: 'black', active: true },
            { name: '耳机', color: 'gray', active: true },
            { name: '充电器', color: 'white', active: false }
          ];
          break;
        case '文具':
          newItems = [
            { name: '笔', color: 'blue', active: true },
            { name: '本子', color: 'yellow', active: false },
            { name: '尺子', color: 'transparent', active: true }
          ];
          break;
      }
      
      this.categories.push({
        name: randomName,
        items: newItems
      });
    }
  }

  shuffleCategories() {
    // 随机打乱分类顺序
    this.categories = [...this.categories].sort(() => Math.random() - 0.5);
  }
}
